<?php

interface ApiPoolValidator 
{
	public function validate($value);
}

class AlwaysTrueValidator implements ApiPoolValidator
{
	public function validate($value) {
		return true;
	}
}

class ApiPoolProtocol
{
	//pacakge
	public static function checkPackageHeader($package) {
		$header = substr($package, 0, 6);
		if (! preg_match('/^[a-fA-F0-9]*$/', $header)) {
			return -1;
		}
		
		$len = strlen($header);
		if ($len < 6) {
			return 0;
		}
		
		$package_len = intval($header, 16);
		if ($package_len > 0xFFFFFF) {
			return -1;
		}
		
		return $package_len;
	}
	
	public static function parsePackage($package) {
		$package_len = self::checkPackageHeader($package);
		if ($package_len <= 0) {
			return null;
		}
		
		$len = strlen($package);
		if ($len < $package_len + 6) {
			return null;
		}
		
		return substr($package, 6, $package_len);
	}
	
	public static function makePackage($content) {
		if ($content == null) {
			return null;
		}
		
		$package_len = strlen($content);
		if ($package_len > 0xFFFFFF) {
			return null;
		}
		
		$header = sprintf('%06x', $package_len);
		return $header.$content;
	}
	
	//Key
    public static function getRequestSrcKey() {
    	return 'src';
    }
    
    public static function getServiceNameApiNameKey() {
    	return 'method';
    }
    
    public static function getParamListKey() {
    	return 'params';
    }
    
    public static function getIdKey() {
    	return 'id';
    }
    
    public static function getCryptTypeKey() {
    	return 'crypttype';
    }
    
    public static function getCryptKeyKey() {
    	return 'cryptkey';
    }
    
    public static function getVersionKey() {
    	return 'version';
    }
    
    public static function getResultKey() {
    	return 'result';
    }
    
    public static function getErrorKey() {
    	return 'error';
    }
    
    public static function getErrorInfoKey() {
    	return 'errorinfo';
    }
    
    public static function getAppErrorCodeKey() {
    	return 'apperrcode';
    }
    
    public static function getAppErrorInfoKey() {
    	return 'errorinfo';
    }
	
    public static function getAppDataKey() {
    	return 'appresdata';
    }
    
    public static function getAppDebugInfoKey() {
    	return 'debuginfo';
    }
    
    //validator
    public static function getRequestSrcValidator() {
    	return self::$s_alway_true_validator;
    }
    
    public static function getServiceNameValidator() {
    	return self::$s_alway_true_validator;
    }
    
    public static function getApiNameValidator() {
    	return self::$s_alway_true_validator;
    }
    
    public static $s_alway_true_validator;
}

ApiPoolProtocol::$s_alway_true_validator = new AlwaysTrueValidator();

?>